<template>
  <a-spin :spinning="loading">
    <a-form ref="formRef" :model="form" :rules="rules" :labelCol="{ span: 4 }" @finish="handleSubmit"
      @finishFailed="handleSubmitFailed">
      <div class="botton-top-contrainer">
        <a-space :size="2">
          <a-button type="primary" html-type="submit">保存</a-button>
          <a-button @click="handleNew">新增</a-button>
          <a-button @click="handleCopy">复制</a-button>
          <a-button @click="handleGoList">列表</a-button>
          <a-button>导出</a-button>
        </a-space>
      </div>

      <a-card>

        <a-row>
          <a-col :span="12">
            <a-form-item ref="schedulingSchemeCode" label="方案编码" name="schedulingSchemeCode">
              <a-input v-model:value="form.schedulingSchemeCode" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item ref="schedulingSchemeName" label="方案名称" name="schedulingSchemeName">
              <a-input v-model:value="form.schedulingSchemeName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item ref="timeFormatName" label="排产时隔" name="timeFormatName">
              <a-input-search v-model:value="form.timeFormatName" @search="handleTimeStep" readonly />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item ref="basicAlgorithm" label="基础算法" name="basicAlgorithm">
              <a-select v-model:value="form.basicAlgorithm">
                <a-select-option :value="1">最短工期</a-select-option>
                <a-select-option :value="2">最早交货期</a-select-option>
                <a-select-option :value="3" disabled>按照交期与工期之间的距离</a-select-option>
                <a-select-option :value="4">CR值</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <JVxeTable keep-source resizable ref="resourceItemRef" :columns="itemColumns"
          :dataSource="form.psPreSchedulingSchemeItemList" :rowNumber="true" :rowSelection="true"
          :disabled="formDisabled" :toolbar="true">
          
        </JVxeTable>

        <TimeSelectModal @register="timeRegister" @getSelectResult="handleTimeStepChanged" />
      </a-card>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, unref, toRaw } from 'vue';
import { useModal } from '/@/components/Modal';
import { useRoute, useRouter } from 'vue-router'
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { itemColumns, rules } from './data/columns';
import { Scheme } from './data'
import TimeSelectModal from '/@/views/components/timeSelectModel.vue';
import { saveOrUpdate, get, getItems } from './api';
import { message } from 'ant-design-vue';

const router = useRouter()
const loading = ref(false)
const route = useRoute()
const formRef = ref()
const form = ref<Scheme>(new Scheme())
const isUpdate = ref(!!route.query.id)
const formDisabled = ref(false);
const resourceItemRef = ref();
const departForItem = ref(false)

const [timeRegister, { openModal: openDepartModal }] = useModal();

function handleTimeStep() {
  departForItem.value = false
  openDepartModal(true, {
    isUpdate: isUpdate.value,
    showFooter: true,
  })
}
function handleTimeStepChanged(value, _options) {

  if (value && form.value) {
    form.value.timeFormatId = value[0].item.id
    form.value.timeFormatName = value[0].item.name
  } 
}

function handleSubmit() {
  try {
    const items = resourceItemRef.value.getTableData()
    if (!items || items.length == 0) {
      throw new Error("资源列表不能为空")
    }

    form.value.psPreSchedulingSchemeItemList = items
    if (form.value && form.value.psPreSchedulingSchemeItemList) {
      loading.value = true
      saveOrUpdate(form.value, isUpdate.value).then(() => {
        if (isUpdate.value) handleLoad()
      }).finally(() => {
        loading.value = false
      })
    }
  } catch (err: any) {
    message.error(err.message)
  }
}
function handleSubmitFailed(errorInfo: any) {
  console.log(errorInfo)
}

function handleLoad() {
  const { id = "" } = route.query
  if (id) {
    loading.value = true
    const _form = ref(null)
    const _items = ref(null)
    const res = get({ id }).then(res => {
      _form.value = res
    })

    const items = getItems({ id }).then(res => {
      _items.value = res
    })

    Promise.all([res, items]).then(() => {
      loading.value = false
      form.value = toRaw(unref(_form))!
      form.value.psPreSchedulingSchemeItemList = toRaw(unref(_items))!
      console.log('form', form.value)
    })
  }
}
function handleNew() {
  isUpdate.value = false
  loading.value = true
  setTimeout(() => {
    form.value = new Scheme()
    loading.value = false
  }, 500)

}
function handleCopy() {
  loading.value = true
  isUpdate.value = false
  form.value.id = null
  form.value.psPreSchedulingSchemeItemList = form.value.psPreSchedulingSchemeItemList.map((item) => {
    item.id = null
    return item
  })
  setTimeout(() => {
    loading.value = false
  }, 500)
}
function handleGoList() {
  router.push({
    name: 'plan-scheduling-feol-resource-index',
    query: {
      t: Date.now()
    }
  })
}
onMounted(() => {
  nextTick(() => { handleLoad() })
})

</script>

<style lang="less" scoped>
.botton-top-contrainer {
  padding: 10px 10px 10px 10px;
}
</style>
